// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_rag_api_serv

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"strings"

	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_rag_api"
)

type QAnythingHistoryItem struct {
	Question string `json:"question"`
	Response string `json:"response"`
}

type QAnythingRequest struct {
	AgentId      string                 `json:"uuid"`
	Question     string                 `json:"question"`
	SourceNeeded string                 `json:"sourceNeeded"`
	History      []QAnythingHistoryItem `json:"history"`
}

type QAnythingAnswerResult struct {
	SingleQAId string `json:"singleQAId"`
	Response   string `json:"response"`
}

type QAnythingAnswerItem struct {
	ErrorCode string                `json:"errorCode"`
	Msg       string                `json:"msg"`
	Result    QAnythingAnswerResult `json:"result"`
}

func (apiImpl *RoadmapRagApiImpl) processQAnything(s roadmap_rag_api.RoadmapRagApi_SendMessageServer, ragConfigItem *roadmap_dao.RagConfigDbItem, ownerUserId, assistantMessageId string, assistantTimeStamp int64) (string, error) {
	ctx := s.Context()
	//列出最近5条内容
	msgItemList, err := roadmap_dao.ChatMessageDao.List(ctx, ragConfigItem.RoadmapId, ragConfigItem.RagConfigId, ownerUserId, math.MaxInt64, roadmap_rag_api.LIST_MESSAGE_TYPE_LIST_MESSAGE_BEFORE, 5)
	if err != nil {
		return "", err
	}
	if len(msgItemList) == 0 {
		return "", fmt.Errorf("miss question")
	}
	lastMsgItem := msgItemList[len(msgItemList)-1]
	if lastMsgItem.ChatRole != roadmap_rag_api.CHAT_ROLE_TYPE_CHAT_ROLE_USER {
		return "", fmt.Errorf("miss question")
	}
	historyList := []QAnythingHistoryItem{}
	if len(msgItemList) == 3 {
		historyList = append(historyList, QAnythingHistoryItem{
			Question: msgItemList[0].Content,
			Response: msgItemList[1].Content,
		})
	}
	if len(msgItemList) == 5 {
		historyList = append(historyList, QAnythingHistoryItem{
			Question: msgItemList[2].Content,
			Response: msgItemList[3].Content,
		})
	}

	//准备请求
	reqUrl := fmt.Sprintf("%s/bot/chat_stream", ragConfigItem.BasicConfig.BaseApiAddr)

	reqData, err := json.Marshal(&QAnythingRequest{
		AgentId:      ragConfigItem.BasicConfig.AgentId,
		Question:     lastMsgItem.Content,
		SourceNeeded: "false",
		History:      historyList,
	})
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", reqUrl, bytes.NewBuffer(reqData))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", ragConfigItem.BasicConfig.ApiKey)
	req.Header.Set("Content-Type", "application/json")

	//处理响应
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	resultContentList := []string{}
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "data:") {
			obj := &QAnythingAnswerItem{}
			err = json.Unmarshal([]byte(line[5:]), obj)
			if err != nil {
				return "", err
			}
			if obj.ErrorCode != "0" {
				return "", fmt.Errorf("%s", obj.Msg)
			}
			done := obj.Result.SingleQAId != ""
			if done {
				break
			} else {
				resultContentList = append(resultContentList, obj.Result.Response)
				s.Send(&roadmap_rag_api.SendMessageResponse{
					Code:                 roadmap_rag_api.SendMessageResponse_CODE_OK,
					UserMessageId:        lastMsgItem.MessageId,
					AssistantTimeStamp:   assistantTimeStamp,
					AssistantMessageId:   assistantMessageId,
					AssistantContentPart: obj.Result.Response,
				})
			}
		}
	}

	return strings.Join(resultContentList, ""), nil
}
